package com.kly.user.task.v2;

import cn.hutool.core.net.NetUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.kly.enums.ParameterTypeEnum;
import com.kly.user.db.dao.UserTaskDetailDao;
import com.kly.user.db.entity.UserTaskDetailEntity;
import com.kly.user.msgClient.ApiClient;
import com.kly.user.task.enums.TaskStatusEnum;
import com.kly.user.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class TaskDetailPushTask {

    private static Log logger = LogFactory.getLog(TaskDetailPushTask.class);
    @NacosValue(value = "${max.execute.times:2}", autoRefreshed = true)
    private Integer maxExecuteTimes;
    @Autowired
    private UserTaskDetailDao userTaskDetailDao;
    @Resource
    ApiClient apiClient;
    @NacosValue(value = "${appsflyer.auth}", autoRefreshed = true)
    private String auth;
    @NacosValue(value = "${task.job.executor.ip}", autoRefreshed = true)
    private String taskJobExecutor;

    private String localIP = NetUtil.getLocalhostStr();


    @Scheduled(fixedDelay = 60000 * 10)
    public void run() {
        if (!taskJobExecutor.contains(localIP)) {
            logger.info("=============NotTaskJobExecutor, currentLocalAddress:{}, onlyExecuteTaskIn:{}", localIP, taskJobExecutor);
            return;
        }
        final List<UserTaskDetailEntity> userTaskDetailEntities = userTaskDetailDao.queryNeedProcessJobs(maxExecuteTimes);
        if (CollectionUtils.isEmpty(userTaskDetailEntities)) {
            return;
        }

        // 推送到msg模块消息
        List<Integer> pushToMsg = Lists.newArrayList(ParameterTypeEnum.MESSAGE_FEEDBACK.getId(),
                ParameterTypeEnum.NORMAL_IMAGE.getId(),
                ParameterTypeEnum.PRIVATE_IMAGE.getId(),
                ParameterTypeEnum.NORMAL_VIDEO.getId(),
                ParameterTypeEnum.PRIVATE_VIDEO.getId(),
                ParameterTypeEnum.WHO_LIKE_ME.getId(),
                ParameterTypeEnum.IM_MSG_PUSH.getId(),
                ParameterTypeEnum.MATCHED_PUSH.getId(),
                ParameterTypeEnum.SYSTEM_NOTICE.getId(),
                ParameterTypeEnum.USER_REST_TIMEOUT.getId(),
                ParameterTypeEnum.REPORT.getId(),
                ParameterTypeEnum.AVATAR_CHANGE.getId()
        );

        userTaskDetailEntities.parallelStream().forEach(o -> {

            if (Objects.isNull(o) || StringUtils.isEmpty(o.getRequest())) {
                updateExecuteStatus(o.getId(), TaskStatusEnum.FAILED.getCode(), null);
                return;
            }

            if (pushToMsg.contains(o.getTaskType())) {
                final JSONObject result = apiClient.post(JSONObject.parseObject(o.getRequest()));
                if (Objects.isNull(result)) {
                    updateExecuteStatus(o.getId(), TaskStatusEnum.FAILED.getCode(), null);
                    return;
                }
                final JSONObject data = result.getJSONObject("data");
                if (Objects.isNull(data)) {
                    updateExecuteStatus(o.getId(), TaskStatusEnum.FAILED.getCode(), null);
                    return;
                }
                final int code = data.getIntValue("code");
                if (code == 0) {
                    updateExecuteStatus(o.getId(), TaskStatusEnum.SUCCESS.getCode(), result.toJSONString());
                } else {
                    updateExecuteStatus(o.getId(), TaskStatusEnum.FAILED.getCode(), result.toJSONString());
                }
            } else if (ParameterTypeEnum.APPFLYER_PUSH.getId().equals(o.getTaskType())) {

                Map<String, String> header = Maps.newConcurrentMap();
                header.put("accept", "application/json");
                header.put("content-type", "application/json");
                header.put("authentication", auth);
                final String result = HttpUtil.postPageBodyByHttps(o.getCallbackUrl(), header, o.getRequest());
                if (StringUtils.isNotEmpty(result) && "ok".equals(result)) {
                    updateExecuteStatus(o.getId(), TaskStatusEnum.SUCCESS.getCode(), result);
                } else {
                    updateExecuteStatus(o.getId(), TaskStatusEnum.FAILED.getCode(), result);
                }
            }
        });


    }



    private void updateExecuteStatus(Long id, Integer status, String result) {
        userTaskDetailDao.updateTask(id, status, result);
    }
}
